package org.metasketch.simulator.configuration.loaders;

import java.io.File;
import java.io.FileReader;
import java.util.List;

import org.metasketch.simulator.resources.Resource;
import org.metasketch.simulator.resources.ResourceBank;
import org.metasketch.simulator.tools.Registry;
import org.metasketch.simulator.transformation.PetriNetSimulationPackage;

import com.thoughtworks.xstream.XStream;

public class StaticConfigLoader {

	protected static XStream getXStream() {
		XStream xstream = new XStream();
		xstream.autodetectAnnotations(true);

		xstream.processAnnotations(Team.class);
		xstream.processAnnotations(SimpleTeam.class);
		xstream.processAnnotations(StaticResourceConfig.class);
		// xstream.processAnnotations(GraphicContainer.class);
		// xstream.processAnnotations(GraphicLink.class);
		// xstream.processAnnotations(GraphicNode.class);
		// xstream.processAnnotations(Diagram.class);

		return xstream;
	}

	protected static StaticResourceConfig load(File file) throws Throwable {

		XStream xstream = getXStream();

		FileReader reader = new FileReader(file);
		StaticResourceConfig cfg = (StaticResourceConfig) xstream
				.fromXML(reader);
		reader.close();

		return cfg;

	}

	public static StaticResourceConfig getStaticResources(
			PetriNetSimulationPackage simulationPackage, File file)
			throws Throwable {
		StaticResourceConfig cfg = load(file);

		// ResourceBank bank = simulationPackage.getResources();
		Registry reg = simulationPackage.getRegistry();

		List<Team> teams = cfg.getTeams();
		for (Team team : teams) {

			if (team instanceof SimpleTeam) {
				SimpleTeam sTeam = (SimpleTeam) team;
				String alias = sTeam.getAlias();

				Resource resource = (Resource) reg.get(alias);

				if (resource == null)
					throw new Exception("No resource found with alias of: "
							+ alias);

				resource.setQuantity(sTeam.getQuantity());
			}

		}

		return cfg;

	}

}
